package net.mycrub.bitwise.ocr.reading;

/**
 * This default filter takes each pixel and computes the scalar product of [r,
 * g, b].[r, g, b] and then normalizes the result [0,0,0]=1, [ff,ff,ff]=0, and
 * then optionally redistributes all the values so that the min is 0 and the max
 * is 1 (if min = max, then min = max = 0)
 */
public class DefaultSampleFilter implements ISampleFilter {

    private boolean redistribute;

    public DefaultSampleFilter() {
        this(false);
    }

    public DefaultSampleFilter(boolean redistribute) {
        this.redistribute = redistribute;
    }

    public double[] filter(int[] pix) {
        double[] result = new double[pix.length];
        double min = 0;
        double max = 0;

        for (int i = 0; i < pix.length; i++) {
            int r = (pix[i] & 0x00ff0000) >> 16;
            int g = (pix[i] & 0x0000ff00) >> 8;
            int b = (pix[i] & 0x000000ff);
            result[i] = (double) (r ^ 2 + g ^ 2 + b ^ 2) / 196608.;

            if (result[i] < min) {
                min = result[i];
            }
            if (result[i] > max) {
                max = result[i];
            }
        }

        if (redistribute) {
            for (int i = 0; i < result.length; i++) {
                if (result[i] <= min) {
                    result[i] = min;
                } else if (result[i] >= max) {
                    result[i] = max;
                } else {
                    result[i] = 1 - (result[i] - min) / (max - min);
                }
            }
        }

        return result;
    }

    public boolean isRedistribute() {
        return redistribute;
    }

    public void setRedistribute(boolean redistribute) {
        this.redistribute = redistribute;
    }

}
